<template>
  <view class="container">
    <u-navbar
      title="选择座位"
      :is-back="true"
    ></u-navbar>
    
    <view class="info-bar">
      <view class="info-item">
        <text class="label">区域:</text>
        <text class="value">{{ areaName }}</text>
      </view>
      <view class="info-item">
        <text class="label">日期:</text>
        <text class="value">{{ date }}</text>
      </view>
      <view class="info-item">
        <text class="label">时段:</text>
        <text class="value">{{ getTimeSlotText(timeSlot) }}</text>
      </view>
    </view>
    
    <view class="legend">
      <view class="legend-item">
        <view class="seat-icon available"></view>
        <text>可选</text>
      </view>
      <view class="legend-item">
        <view class="seat-icon occupied"></view>
        <text>已占</text>
      </view>
      <view class="legend-item">
        <view class="seat-icon selected"></view>
        <text>已选</text>
      </view>
      <view class="legend-item">
        <view class="seat-icon disabled"></view>
        <text>不可用</text>
      </view>
    </view>
    
    <scroll-view scroll-y class="seat-container">
      <view class="seat-map">
        <view class="entrance">入口</view>
        
        <view class="seat-row" v-for="(row, rowIndex) in seatMap" :key="rowIndex">
          <view 
            class="seat-item" 
            v-for="(seat, colIndex) in row" 
            :key="colIndex"
            :class="{
              'available': seat.status === 'available',
              'occupied': seat.status === 'occupied',
              'selected': selectedSeatId === seat.id,
              'disabled': seat.status === 'disabled',
              'empty': seat.status === 'empty'
            }"
            @click="selectSeat(seat)"
          >
            <text v-if="seat.status !== 'empty'">{{ seat.name }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <view class="bottom-bar" v-if="selectedSeatId">
      <view class="selected-info">
        <text class="label">已选座位:</text>
        <text class="value">{{ selectedSeatName }}</text>
      </view>
      <u-button type="primary" @click="confirmSeat">确认选择</u-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      areaId: '',
      areaName: '',
      date: '',
      timeSlot: '',
      seatMap: [],
      selectedSeatId: '',
      selectedSeatName: '',
      reserveData: {}
    }
  },
  onLoad(options) {
    this.areaId = options.areaId || ''
    this.date = options.date || ''
    this.timeSlot = options.timeSlot || ''
    
    // 获取预约数据
    const reserveData = uni.getStorageSync('reserveData')
    if (reserveData) {
      this.reserveData = JSON.parse(reserveData)
      this.areaName = this.reserveData.areaName
      
      // 如果已有选中的座位，设置选中状态
      if (this.reserveData.seatId) {
        this.selectedSeatId = this.reserveData.seatId
        this.selectedSeatName = this.reserveData.seatName
      }
    }
    
    // 获取座位数据
    this.getSeats()
  },
  methods: {
    // 获取时段文本
    getTimeSlotText(timeSlot) {
      const timeSlotTextMap = {
        'morning': '上午 (8:00-12:00)',
        'afternoon': '下午 (13:00-17:00)',
        'evening': '晚上 (18:00-22:00)',
        'allday': '全天 (8:00-22:00)'
      }
      return timeSlotTextMap[timeSlot] || '未知时段'
    },
    
    // 获取座位数据
    async getSeats() {
      if (!this.areaId || !this.date || !this.timeSlot) {
        uni.showToast({
          title: '参数不完整',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '加载中'
        })
        
        const res = await this.$api.getSeats({
          area_id: this.areaId,
          date: this.date,
          time_slot: this.timeSlot
        })
        
        uni.hideLoading()
        
        if (res.data && res.data.code === 200) {
          // 处理座位数据，转换为二维数组形式的座位地图
          this.processSeatData(res.data.data)
        } else {
          uni.showToast({
            title: res.data.message || '获取座位数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('获取座位数据失败', error)
        uni.showToast({
          title: '获取座位数据失败',
          icon: 'none'
        })
      }
    },
    
    // 处理座位数据
    processSeatData(seats) {
      // 获取最大行列数
      let maxRow = 0
      let maxCol = 0
      
      seats.forEach(seat => {
        maxRow = Math.max(maxRow, seat.row_index)
        maxCol = Math.max(maxCol, seat.column_index)
      })
      
      // 初始化座位地图
      const seatMap = []
      for (let i = 0; i <= maxRow; i++) {
        const row = []
        for (let j = 0; j <= maxCol; j++) {
          row.push({
            id: '',
            name: '',
            status: 'empty',
            row_index: i,
            column_index: j
          })
        }
        seatMap.push(row)
      }
      
      // 填充座位数据
      seats.forEach(seat => {
        seatMap[seat.row_index][seat.column_index] = {
          id: seat.id,
          name: seat.name,
          status: seat.status,
          row_index: seat.row_index,
          column_index: seat.column_index
        }
      })
      
      this.seatMap = seatMap
    },
    
    // 选择座位
    selectSeat(seat) {
      if (seat.status === 'available') {
        this.selectedSeatId = seat.id
        this.selectedSeatName = seat.name
      } else if (seat.status === 'occupied') {
        uni.showToast({
          title: '该座位已被占用',
          icon: 'none'
        })
      } else if (seat.status === 'disabled') {
        uni.showToast({
          title: '该座位不可用',
          icon: 'none'
        })
      } else if (seat.status === 'empty') {
        // 空位置，不做任何操作
      }
    },
    
    // 确认选择座位
    confirmSeat() {
      if (!this.selectedSeatId) {
        uni.showToast({
          title: '请选择座位',
          icon: 'none'
        })
        return
      }
      
      // 更新预约数据
      this.reserveData.seatId = this.selectedSeatId
      this.reserveData.seatName = this.selectedSeatName
      
      // 保存预约数据
      uni.setStorageSync('reserveData', JSON.stringify(this.reserveData))
      
      // 返回上一页
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.info-bar {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  
  .info-item {
    display: flex;
    align-items: center;
    
    .label {
      font-size: 26rpx;
      color: #666;
      margin-right: 10rpx;
    }
    
    .value {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.legend {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  
  .legend-item {
    display: flex;
    align-items: center;
    
    .seat-icon {
      width: 40rpx;
      height: 40rpx;
      border-radius: 6rpx;
      margin-right: 10rpx;
      
      &.available {
        background-color: #1A8DFF;
      }
      
      &.occupied {
        background-color: #ff4d4f;
      }
      
      &.selected {
        background-color: #52c41a;
      }
      
      &.disabled {
        background-color: #d9d9d9;
      }
    }
    
    text {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.seat-container {
  flex: 1;
  padding: 20rpx;
  background-color: #ffffff;
}

.seat-map {
  width: 100%;
  position: relative;
  padding: 20rpx;
  
  .entrance {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    background-color: #ffd591;
    color: #873800;
    padding: 10rpx 30rpx;
    border-radius: 0 0 20rpx 20rpx;
    font-size: 24rpx;
  }
}

.seat-row {
  display: flex;
  justify-content: center;
  margin-bottom: 20rpx;
}

.seat-item {
  width: 80rpx;
  height: 80rpx;
  margin: 0 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 10rpx;
  font-size: 24rpx;
  color: #ffffff;
  
  &.available {
    background-color: #1A8DFF;
  }
  
  &.occupied {
    background-color: #ff4d4f;
  }
  
  &.selected {
    background-color: #52c41a;
  }
  
  &.disabled {
    background-color: #d9d9d9;
  }
  
  &.empty {
    background-color: transparent;
  }
}

.bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  
  .selected-info {
    display: flex;
    align-items: center;
    
    .label {
      font-size: 28rpx;
      color: #666;
      margin-right: 10rpx;
    }
    
    .value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}
</style>
